package com.zzg.springboot.redis.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.zzg.springboot.redis.util.RedisUtil;

@Configuration
@EnableCaching
public class RedisConfig {
	// 获取Jedis 连接工厂对象
	@Bean
	public JedisConnectionFactory getConnectionFactory() {
		return new JedisConnectionFactory();
	}

	@Bean
	public RedisTemplate<String, Object> redisTemplate() {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

		JedisConnectionFactory factory = getConnectionFactory();
		// 设置Jedis 连接工厂对象
		redisTemplate.setConnectionFactory(factory);
		// 设置是否启动事务
		redisTemplate.setEnableTransactionSupport(true);
		// 设置Key 序列化方式
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		// 设置Hash Key 序列化方式
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		// 设置Hash Value 序列化方式
		redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		// 设置Value 序列化方式
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

		// 动态更新redisTemplate 设置
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}
	
	/**
     * 配置CacheManager 管理cache
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); 
        cacheManager.setDefaultExpiration(60*60); // 设置key-value超时时间
        return cacheManager;
    }


	@Bean(name = "redisUtil")
	public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
		RedisUtil redisUtil = new RedisUtil();
		redisUtil.setRedisTemplate(redisTemplate);
		return redisUtil;
	}

}
